const Router = require('@koa/router');
const { genUserTicket, validateUserPwd, validateTicketUser } = require('../service/user');
const { clearUserSession } = require('../service/session');

const router = new Router();

router.prefix('/auth');

module.exports = router;

/**
 * 登录页面
 */
router.get('/login', async (ctx, next) => {
  const { user } = ctx.session;
  const { appName } = process.env;

  if (user && user.id) {
    if (ctx.query.redirect) {
      const ticket = genUserTicket(user.id);

      ctx.redirect(`${ctx.query.redirect}?ticket=${ticket}`);
      return;
    }

    ctx.redirect('/', { user });
    return;
  }
  await ctx.render('login', { appName });
  next();
});

router.post('/login', async (ctx, next) => {
  const { body, query } = ctx.request;

  const { name, password } = body;

  const user = await validateUserPwd(name, password);
  if (!user) {
    ctx.body = { error: 1, message: '用户名或密码错误' };
    return;
  }
  ctx.session.user = user;

  if (query.redirect) {
    const ticket = genUserTicket(user.id);
    ctx.redirect(`${query.redirect}?ticket=${ticket}`);
    return;
  }

  ctx.redirect('/');
  next();
});

router.post('/validate', async (ctx, next) => {
  const { ticket } = ctx.request.query;

  const user = await validateTicketUser(ticket);
  if (!user) {
    ctx.body = {
      error: 1,
      message: '验证失败',
    };
    return;
  }

  ctx.body = { error: 0, messae: null, user };
  next();
});

router.get('/logout', async (ctx, next) => {
  const uid = ctx.query.uid || ctx.session?.user?.id;
  console.log('logout called', uid);

  if (ctx.session.user) {
    ctx.session = null;
  }

  if (uid) {
    await clearUserSession(ctx.query.uid);

    ctx.body = { error: 0, message: null };
    return;
  }
  next();
});
